#include "RWLock.h"

RWLock :: Lightswitch :: Lightswitch(){
    counter = 0;
    mutex_ls = PTHREAD_MUTEX_INITIALIZER;
    pthread_mutex_init(&mutex_ls, NULL);
}

RWLock :: Lightswitch :: ~Lightswitch(){
        pthread_mutex_destroy(&mutex_ls);

}

void RWLock :: Lightswitch :: lock(pthread_mutex_t * semaphore){
    pthread_mutex_lock(&(this->mutex_ls));
    this->counter += 1;
    if (this->counter == 1 ){
        pthread_mutex_lock(semaphore);
    }
    pthread_mutex_unlock(&(this->mutex_ls));

}
void RWLock :: Lightswitch :: unlock(pthread_mutex_t* semaphore){
    pthread_mutex_lock(&(this->mutex_ls));
    this->counter -= 1;
    if (this->counter == 0){
        pthread_mutex_unlock(semaphore);
    }
    pthread_mutex_unlock(&(this->mutex_ls));

}

RWLock :: RWLock() {
    ls = Lightswitch();
    turnstile = PTHREAD_MUTEX_INITIALIZER;
    roomEmpty = PTHREAD_MUTEX_INITIALIZER;

    pthread_mutex_init(&turnstile, NULL);
    pthread_mutex_init(&roomEmpty, NULL);
}
RWLock  ::  ~RWLock(){
    pthread_mutex_destroy(&turnstile);
    pthread_mutex_destroy(&roomEmpty);
}


void RWLock :: rlock() {
    pthread_mutex_lock(&(turnstile));
    pthread_mutex_unlock(&(turnstile));
    ls.lock(&roomEmpty);
    
}

void RWLock :: wlock() {
    pthread_mutex_lock(&(turnstile));
    pthread_mutex_lock(&(roomEmpty));


}

void RWLock :: runlock() {
        ls.unlock(&roomEmpty);

}

void RWLock :: wunlock() {
    pthread_mutex_unlock(&(turnstile));
    pthread_mutex_unlock(&(roomEmpty));


}